package cn.catsdad.util;

import cn.catsdad.constant.ICommonWarningType;
import cn.hutool.core.lang.Snowflake;

import java.util.Map;

/**
 * 雪花id工具
 *
 * @author xuyl
 * @version 1.0 2024/5/26
 */
@SuppressWarnings(ICommonWarningType.UNUSED)
public class SnowflakeIdUtil {

    private static final String SNOWFLAKE_WORKER_ID = "app.snowflake.workerId";
    private static final String SNOWFLAKE_DATA_CENTER_ID = "app.snowflake.dataCenterId";
    private static volatile Snowflake snowflake;

    /**
     * 获取雪花id
     *
     * @return 雪花id
     */
    public static Long getSnowflakeId() {
        if (snowflake == null)
            initSnowflake();
        return snowflake.nextId();
    }

    /**
     * 初始化雪花生成器，用于保证不同服务之前生成id不会重复
     */
    private synchronized static void initSnowflake() {
        Map<String, Integer> snowflakeConfigs = EnvironmentUtil
                .getProperties(new EnvironmentUtil.PropertyParam<Integer>()
                        .setKey(SNOWFLAKE_WORKER_ID)
                        .setValueType(Integer.class)
                        .setDefaultValue(1), new EnvironmentUtil.PropertyParam<Integer>()
                        .setKey(SNOWFLAKE_DATA_CENTER_ID)
                        .setValueType(Integer.class)
                        .setDefaultValue(1));
        Integer workerId = snowflakeConfigs.get(SNOWFLAKE_WORKER_ID);
        Integer dataCenterId = snowflakeConfigs.get(SNOWFLAKE_DATA_CENTER_ID);
        snowflake = new Snowflake(workerId, dataCenterId);
    }

}
